package com.zaoqi.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zaoqi.anno.Log;
import com.zaoqi.mapper.UserMapper;
import com.zaoqi.pojo.PageBean;
import com.zaoqi.pojo.User;
import com.zaoqi.service.UserService;
import com.zaoqi.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    @Log
    public PageBean getUsers(int pageNum, int pageSize, String username) {
        PageHelper.startPage(pageNum, pageSize);
        List<User> users = userMapper.selectUsersByName(username);
        PageInfo<User> pageInfo = new PageInfo<>(users);
        return new PageBean(pageInfo.getTotal(), pageInfo.getList());
    }
    @Override
    @Log
    public void createUser(User user) {
        // 插入用户数据，MyBatis 会自动返回生成的主键并填充到 User 对象的 id 字段
        int rows = userMapper.createUser(user);
        // 检查插入操作是否成功
        if (rows > 0) {
            System.out.println("用户创建成功，ID: " + user.getId());
        } else {
            throw new RuntimeException("用户创建失败");
        }
    }
    @Override
    @Log
    public boolean deleteUserByUsername(String username) {
        // 先根据用户名找到用户 ID
        User user = userMapper.findByUsername(username);
        if (user == null) {
            return false; // 用户不存在
        }
        // 删除用户
        userMapper.deleteUserByUsername(username);
        return true;
    }
    @Override
    @Log
    public boolean updateUser(Long id, User updatedUser) {
        User existingUser = userMapper.findById(id);
        if (updatedUser == null)
            log.info("数据格式错误或未填写完全");
        if (existingUser != null) {
            userMapper.updateUser(id, updatedUser);
            return true;
        }
        return false;
    }
    @Override
    public boolean isAdmin(String token) {
        Claims claims = JwtUtils.parseJWT(token.replace("Bearer ", ""));
        String role = (String) claims.get("role");
        if("admin".equals(role)){
            log.info("管理员执行操作");
            return true;
        }else{
            log.info("用户权限不足，仅管理员能执行该操作");
            return false;
        }
    }
}
